package com.wang.interceptor;

import com.wang.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 定义拦截器
 */
public class LoginHandlerInterceptor implements HandlerInterceptor {

    @Autowired
    RedisUtil redisUtil = new RedisUtil();

    //调用目标方法之前被拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies = request.getCookies();
        if(cookies != null){
            for(Cookie co : cookies){
                String name = co.getName();
                String value = co.getValue();
                try {
                    if (value != null && redisUtil.get(name) != null){
                        if (value.equals(redisUtil.get(name))){
                            return true;
                        }
                    }
                } catch (Exception e) {
                    System.out.println(e);
                }
            }
        }
        request.setAttribute("msg","没有权限，请先登陆！");
        response.sendRedirect(request.getContextPath()+"/");
        return false;
    }
}
